<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight" class="bread-crumb">
      <el-breadcrumb-item :to="{ path: '/' }">
        <el-icon>
          <HomeFilled/>
        </el-icon>
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{ cateName }}</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="cate-card">
      <ul class="cate-list">
        <li class="c-list-item">
          <p class="c-label">分类：</p>
          <ul class="c-value-list">
            <li
                class="c-val-item"
                v-for="(item, index) in cateList"
                :key="index"
                @click="(val) => filterCate(item, index, 0)"
                :class="{ 'select-tag': currCateIndex[0] == index }"
            >
              {{ item.name }}
            </li>
          </ul>
        </li>
        <li class="c-list-item" v-if="lv2">
          <p class="c-label">二级分类：</p>
          <ul class="c-value-list">
            <li
                class="c-val-item"
                v-for="(item, index) in cateList[currCateIndex[0]].children"
                :key="item.catId"
                @click="(val) => filterCate(item, index, 1)"
                :class="{
                'select-tag':
                  currCateIndex.length > 1 && currCateIndex[1] == index,
              }"
            >
              {{ item.name }}
            </li>
          </ul>
        </li>
        <li class="c-list-item" v-if="lv3">
          <p class="c-label">三级分类：</p>
          <ul class="c-value-list">
            <li
                class="c-val-item"
                v-for="(item, index) in cateList[currCateIndex[0]].children[
                currCateIndex[1]
              ].children"
                :key="item.catId"
                @click="(val) => filterCate(item, index, 2)"
                :class="{
                'select-tag':
                  currCateIndex.length > 2 && currCateIndex[2] == index,
              }"
            >
              {{ item.name }}
            </li>
          </ul>
        </li>
        <li
            class="c-list-item"
            v-show="currCategory.brands && currCategory.brands.length > 0"
        >
          <p class="c-label">品牌：</p>
          <ul class="c-value-list">
            <li
                class="c-val-item"
                v-for="(item, index) in currCategory.brands"
                :key="index"
                @click="selectTag(SelectType.BRAND, item)"
                :class="{ 'select-tag': brand.brandId == item.brandId }"
            >
              {{ item.brandName }}
            </li>
          </ul>
        </li>
        <template v-for="(attr, index) in currCategory.attrs">
          <li
              class="c-list-item"
              :key="index"
              v-if="!attrs.find((item) => item.attrId == attr.attrId)"
          >
            <p class="c-label">{{ attr.attrName }} :</p>
            <ul class="c-value-list">
              <li
                  class="c-val-item"
                  v-for="(tag, _index) in attr.valueSelect"
                  @click="(val) => selectTag(SelectType.ATTR, attr, tag)"
                  :key="_index"
              >
                {{ tag }}
              </li>
            </ul>
          </li>
        </template>

        <li class="c-list-item">
          <p class="c-label">已选择：</p>
          <ul class="c-value-list">
            <li
                class="select-tag"
                v-for="item in cate"
                :key="item.catId"
                @click="removeTag(SelectType.CATE, item)"
            >
              {{ item.label }}：{{ item.name }}
              <el-icon>
                <Close/>
              </el-icon>
            </li>
            <li
                class="select-tag"
                v-if="form.brand.brandId"
                @click="removeTag(SelectType.BRAND, form.brand)"
            >
              品牌：{{ form.brand.brandName }}
              <el-icon>
                <Close/>
              </el-icon>
            </li>
            <li
                class="select-tag"
                v-for="attr in attrs"
                :key="attr.attrId"
                @click="removeTag(SelectType.ATTR, attr)"
            >
              {{ attr.attrName }}：{{ attr.attrValue }}
              <el-icon>
                <Close/>
              </el-icon>
            </li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 商品列表 -->
    <section class="product-section">
      <el-row :gutter="20">
        <el-col :span="5" v-for="item in productList" :key="item.skuId">
          <ProductCard :product="item"/>
        </el-col>
      </el-row>
      <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="form.pageNum"
          :limit.sync="form.pageSize"
          @pagination="getList"
          class="pagination"
      />
    </section>
  </div>
</template>

<script setup>
import {ArrowRight} from "@element-plus/icons-vue";
import {useRoute, useRouter} from "vue-router";
import ProductCard from "@/components-mall/ProductCard";
import {getSearchOptions, findOriginCategories} from "@/api/mall/client/cate/index";
import {computed, reactive, ref, toRefs, watch} from "vue";
import {search} from "@/api/mall/client/product/index";

const router = useRouter();
const route = useRoute();

// 获取路由参数
const query = route.query;
// 获取cateName
const cateName = ref("分类");

// 获取所有分类
const cateList = ref([]);
const getCateList = async () => {
  const res = await getSearchOptions();
  cateList.value = res.data.categories;
};

const currCateIndex = ref([0]);
// 当前类别
const currCategory = ref({});

// 表单
const form = reactive({
  cate: [],
  attrs: [],
  brand: {},
  brandId: null,
  catId: null,
  pageNum: 1,
  pageSize: 10,
});
// 查询商品
const productList = ref([]);
const total = ref(0);
const handleSearch = async () => {
  form.brandId = brand.value.brandId;
  form.catId = cate.value[cate.value.length - 1].catId;
  const res = await search(form);
  productList.value = res.rows;
  total.value = res.total;
};
const {cate, attrs, brand} = toRefs(form);
watch(
    () => form,
    (val) => {
      console.log("form改变了");
      console.log(form);
      handleSearch();
    },
    {
      deep: true,
    }
);
watch(
    () => brand.value,
    (val) => {
      form.brandId = val.brandId;
    },
    {
      deep: true,
    }
);
watch(
    () => cate.value,
    (val) => {
      console.log(cate.value);
      form.catId = cate.value[val.length - 1].catId;
    },
    {
      deep: true,
    }
);
/**
 *
 * @param {*} item 当前categoryList对象
 * @param {*} index 选中tag的索引
 * @param {*} level 当前的层级
 */
const filterCate = (item, index, level) => {
  currCategory.value = item;
  console.log("当前的currCategory", currCategory.value);
  // 处理层级
  switch (level) {
    case 0:
      if (lv3.value){
        lv3.value = false;
      }
      currCateIndex.value = [index];
      cate.value.splice(1, 2);
      cate.value = [
        {
          label: "分类",
          catId: currCategory.value.catId,
          name: currCategory.value.name,
        },
      ];
      lv2.value = hasChildren(item);
      // 清除attrbrand
      attrs.value = [];
      brand.value = {};
      break;
    case 1:
      currCateIndex.value = [currCateIndex.value[0], index];
      lv3.value = hasChildren(item);
      const lv2cate = cate.value.find((item) => item.label == "二级分类");
      cate.value.splice(2, 1);
      console.log(lv2cate);
      if (lv2cate) {
        console.log("lv2cate", item);
        cate.value[1].catId = item.catId;
        cate.value[1].name = item.name;
      } else {
        cate.value.push({
          label: "二级分类",
          catId: item.catId,
          name: item.name,
        });
      }
      attrs.value = [];
      brand.value = {};
      break;
    case 2:
      currCateIndex.value = [
        currCateIndex.value[0],
        currCateIndex.value[1],
        index,
      ];
      const lv3cate = cate.value.find((item) => item.label == "三级分类");
      if (lv3cate) {
        cate.value[2].catId = item.catId;
        cate.value[2].name = item.name;
      } else {
        cate.value.push({
          label: "三级分类",
          catId: item.catId,
          name: item.name,
        });
      }
      attrs.value = [];
      brand.value = {};
      break;
    default:
      break;
  }
  // 处理attrs的valueSelect字段
  if (currCategory.value.attrs) {
    currCategory.value.attrs.forEach((attr) => {
      if (typeof attr.valueSelect == "string") {
        attr.valueSelect = attr.valueSelect.split(",");
      }
    });
  }
  // if (form.catId) {
  //   handleSearch();
  // }
};
watch(
    () => currCateIndex.value,
    (val) => {
      console.log(val);
    },
    {
      deep: true,
    }
);

/**
 * 选中
 * @param {*} e 类别：分类、品牌
 * @param {*} item 父list
 * @param {*} tag 选中元素
 */
const selectTag = (type, item, tag) => {
  switch (type) {
    case SelectType.CATE:
      break;
    case SelectType.ATTR:
      // 如果是attr
      // 去重
      const index = attrs.value.findIndex((attr) => attr.attrId == item.attrId);
      if (index == -1) {
        attrs.value.push({
          attrId: item.attrId,
          attrName: item.attrName,
          attrValue: tag,
        });
      } else {
        attrs.value[index].attrValue = tag;
      }
      break;
    case SelectType.BRAND:
      form.brand = item;
      break;
    default:
      break;
  }
  console.log("FORM", form);
  // if (form.catId) {
  //   handleSearch();
  // }
};
const SelectType = Object.freeze({
  CATE: "cate",
  BRAND: "brand",
  ATTR: "attr",
});
// 删除tag
const removeTag = (type, item) => {
  // 如果是attr
  switch (type) {
    case SelectType.ATTR:
      attrs.value = attrs.value.filter((attr) => attr.attrId != item.attrId);
      break;
    case SelectType.BRAND:
      form.brand = {};
      break;
    case SelectType.CATE:
      console.log(cate.value);
      // 找到层级
      const cIndex = cate.value.findIndex((c) => c.catId == item.catId);
      console.log(cIndex);

      if (cIndex == 0) {
        // 顶级分类
        if (lv3.value) {
          // 如果原本3级是选中的再切到一个没有3级的，不关掉，lv3 catId 会 undifined
          lv3.value = false;
        }
        if (lv2.value) {
          currCateIndex.value = [cIndex]
        }
        cate.value = [];
        cate.value.push({
          label: "分类",
          catId: item.catId,
          name: item.name,
        });
          attrs.value = [];
          brand.value = {};
        break;
      }
      if (cIndex == 1) {
        lv3.value = false;
        currCategory.value = cateList.value[currCateIndex.value[0]];
      }
      if (cIndex == 2) {
        currCategory.value =
            cateList.value[currCateIndex.value[0]].children[
                currCateIndex.value[1]
                ];
      }
      cate.value.splice(cIndex, cate.value.length - cIndex);

      currCateIndex.value.splice(cIndex, currCateIndex.value.length - cIndex);
      console.log("&&&&&");
      console.log(cate.value);
      console.log(currCateIndex.value);
      console.log(currCategory.value);
      // 还要把剩下的细分置空
      attrs.value = [];
      brand.value = {};
      break;
    default:
      break;
  }
  // if (form.catId) {
  //   handleSearch();
  // }
};
getCateList().then((res) => {
  if (query.catId) {
    // 找到对应cate的下标

    const index = cateList.value.findIndex((c) => c.catId == query.catId);
    console.log("CATiD", index);
    currCateIndex.value[0] = index;
    filterCate(cateList.value[index], index, 0);
    // filterCate(cateList.value[])
  } else {
    filterCate(cateList.value[0], 0, 0);
  }
});


watch(() => query.catalogId, () => {
  const catalogId = query.catalogId
  if (catalogId !== undefined) {
    if (catalogId !== undefined) {
      findOriginCategories(catalogId).then((res) => {
        cate.value = ref([]);
        const title = ref("分类")
        res.data.forEach((item) => {
          if (item.catLevel == 1) {
            currCateIndex.value[0] = cateList.value.findIndex((c) => c.catId == item.catId);
          } else if (item.catLevel == 2) {
            currCateIndex.value[1] = cateList.value[currCateIndex.value[0]].children.findIndex((c) => c.catId == item.catId);
            title.value = "二级分类";
            lv3.value = hasChildren(cateList.value[currCateIndex.value[0]].children[currCateIndex.value[1]]);
          } else if (item.catLevel == 3) {
            currCateIndex.value[2] = cateList.value[currCateIndex.value[0]].children[currCateIndex.value[1]].children.findIndex((c) => c.catId == item.catId);
            title.value = "三级分类";
          }
          cate.value.push({
            label: title.value,
            catId: item.catId,
            name: item.name,
          });
        });

      })
    }
  }
}, {immediate: true})


// 判断children是否存在
const lv2 = ref(false);
const lv3 = ref(false);
const hasChildren = (item) => {
  if (item) {
    if (item.children && item.children.length > 0) {
      return true;
    }
  }
  return false;
};
</script>

<style lang="scss" scoped>
:deep(.pagination-container) {
  background: #ffffff00 !important;
  margin-bottom: 10px;
  padding: 32px 16px !important;
  height: 0 !important;
}

:deep(.el-pagination) {
  --el-pagination-hover-color: #1aa684;
  --el-color-primary: #1aa684;

  background: none;
}

:deep(.el-select-dropdown__item.selected) {
  color: #1aa684 !important;
}

.select-tag {
  margin: 5px 10px;
  padding: 3px 8px;
  background: #1aa684;
  color: #fff;
  display: flex;
  align-items: center;

  .el-icon {
    margin-left: 5px;
  }

  :deep(.el-breadcrumb__inner a:hover, .el-breadcrumb__inner.is-link:hover) {
    color: #1aa684;
  }
}

p {
  margin: 0;
}

.bread-crumb {
  padding: 20px 0;
}

.cate-card {
  background: #fff;
  padding: 20px;
}

.cate-list {
  .c-list-item {
    display: flex;
    align-items: start;
    font-size: 14px;

    .c-label {
      min-width: 50px;
      padding-top: 5px;
    }

    .c-value-list {
      display: flex;
      flex-wrap: wrap;

      .c-val-item {
        margin: 5px 5px;
        padding: 3px 8px;

        &:hover {
          background: #1aa684;
          color: #fff;
        }
      }
    }
  }
}

.product-section {
  margin-top: 30px;
  padding-bottom: 10px;
}

.el-col-5 {
  width: 20%;
  max-width: 20%;
  flex: 0 0 20%;
}
</style>
